/**
 * 微信小程序前端调用示例
 * 用户动态服务API调用
 */

// 基础配置
const API_BASE_URL = 'http://115.190.125.125:8082'; // 网关地址
const DYNAMIC_API = `${API_BASE_URL}/api/dynamic`;

/**
 * 封装请求方法
 */
function request(url, method = 'GET', data = {}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          resolve(res.data.data);
        } else {
          wx.showToast({
            title: res.data.message || '请求失败',
            icon: 'none'
          });
          reject(res.data);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
}

/**
 * 动态服务API
 */
const DynamicAPI = {
  
  /**
   * 获取动态列表（推荐）
   * @param {Number} pageNum 页码
   * @param {Number} pageSize 每页大小
   * @param {Number} userId 当前用户ID
   */
  getRecommendList(pageNum = 1, pageSize = 10, userId = null) {
    const params = {
      pageNum,
      pageSize
    };
    if (userId) {
      params.userId = userId;
    }
    return request(`${DYNAMIC_API}/recommend`, 'GET', params);
  },

  /**
   * 获取动态详情
   * @param {Number} dynamicId 动态ID
   * @param {Number} userId 当前用户ID
   */
  getDynamicDetail(dynamicId, userId = null) {
    const params = {};
    if (userId) {
      params.userId = userId;
    }
    return request(`${DYNAMIC_API}/detail/${dynamicId}`, 'GET', params);
  },

  /**
   * 获取某个用户的动态列表
   * @param {Number} targetUserId 目标用户ID
   * @param {Number} pageNum 页码
   * @param {Number} pageSize 每页大小
   * @param {Number} currentUserId 当前用户ID
   */
  getUserDynamics(targetUserId, pageNum = 1, pageSize = 10, currentUserId = null) {
    const params = {
      pageNum,
      pageSize
    };
    if (currentUserId) {
      params.currentUserId = currentUserId;
    }
    return request(`${DYNAMIC_API}/user/${targetUserId}`, 'GET', params);
  },

  /**
   * 健康检查
   */
  health() {
    return request(`${DYNAMIC_API}/health`, 'GET');
  }
};

/**
 * 使用示例
 */

// 示例1：在页面加载时获取推荐动态列表
Page({
  data: {
    dynamicList: [],
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    currentUserId: 1 // 从全局状态或登录信息中获取
  },

  onLoad() {
    this.loadDynamicList();
  },

  // 加载动态列表
  async loadDynamicList() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      const result = await DynamicAPI.getRecommendList(
        this.data.pageNum,
        this.data.pageSize,
        this.data.currentUserId
      );

      this.setData({
        dynamicList: this.data.pageNum === 1 ? result.records : [...this.data.dynamicList, ...result.records],
        hasMore: result.current < result.pages
      });

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      console.error('加载动态列表失败', error);
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({ pageNum: 1 });
    await this.loadDynamicList();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  async onReachBottom() {
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none'
      });
      return;
    }

    this.setData({
      pageNum: this.data.pageNum + 1
    });
    await this.loadDynamicList();
  },

  // 查看动态详情
  async viewDynamicDetail(e) {
    const dynamicId = e.currentTarget.dataset.id;
    try {
      const detail = await DynamicAPI.getDynamicDetail(dynamicId, this.data.currentUserId);
      
      // 跳转到详情页面，传递数据
      wx.navigateTo({
        url: `/pages/dynamic/detail?id=${dynamicId}`
      });
    } catch (error) {
      console.error('查看详情失败', error);
    }
  }
});

// 示例2：在用户主页查看该用户的动态
Page({
  data: {
    targetUserId: 0,
    currentUserId: 1,
    dynamicList: [],
    pageNum: 1,
    pageSize: 10
  },

  onLoad(options) {
    this.setData({
      targetUserId: options.userId || 0
    });
    this.loadUserDynamics();
  },

  async loadUserDynamics() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      const result = await DynamicAPI.getUserDynamics(
        this.data.targetUserId,
        this.data.pageNum,
        this.data.pageSize,
        this.data.currentUserId
      );

      this.setData({
        dynamicList: result.records
      });

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      console.error('加载用户动态失败', error);
    }
  }
});

// 示例3：动态列表WXML模板
/*
<view class="dynamic-list">
  <block wx:for="{{dynamicList}}" wx:key="dynamicId">
    <view class="dynamic-item" bindtap="viewDynamicDetail" data-id="{{item.dynamicId}}">
      <!-- 用户信息 -->
      <view class="user-info">
        <image class="avatar" src="{{item.user.avatarUrl}}" mode="aspectFill"></image>
        <text class="nickname">{{item.user.nickname}}</text>
        <text class="time">{{item.createdAt}}</text>
      </view>
      
      <!-- 动态内容 -->
      <view class="content">{{item.content}}</view>
      
      <!-- 媒体文件 -->
      <view class="media-list" wx:if="{{item.mediaUrls.length > 0}}">
        <block wx:for="{{item.mediaUrls}}" wx:key="index" wx:for-item="url">
          <image class="media-image" src="{{url}}" mode="aspectFill"></image>
        </block>
      </view>
      
      <!-- 互动信息 -->
      <view class="interaction">
        <view class="item">
          <image src="/static/like.png" class="icon"></image>
          <text>{{item.likeCount}}</text>
        </view>
        <view class="item">
          <image src="/static/comment.png" class="icon"></image>
          <text>{{item.commentCount}}</text>
        </view>
        <view class="item">
          <image src="/static/favorite.png" class="icon"></image>
          <text>{{item.favoriteCount}}</text>
        </view>
      </view>
    </view>
  </block>
</view>
*/

// 示例4：使用app.js全局配置
// 在app.js中可以这样配置
/*
App({
  globalData: {
    apiBaseUrl: 'http://115.190.125.125:8082',
    currentUserId: null
  },

  onLaunch() {
    // 检查登录状态
    this.checkLogin();
  },

  checkLogin() {
    const userId = wx.getStorageSync('userId');
    if (userId) {
      this.globalData.currentUserId = userId;
    }
  },

  // 获取API基础URL
  getApiBaseUrl() {
    return this.globalData.apiBaseUrl;
  },

  // 获取当前用户ID
  getCurrentUserId() {
    return this.globalData.currentUserId;
  }
});
*/

// 导出API对象（如果使用模块化）
export default DynamicAPI;


